<template>
  <div style="padding-left: 0.5rem;padding-right: 0.3rem;">
    <h3>敲出收益管理</h3>
    <div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="观察开始日" class="dialog-form-item">
            <el-row>
              <el-col :span="12">
                <el-date-picker value-format="YYYY-MM-DD" v-model="tableData.form.startDate"
                                type="date"
                                placeholder=""/>
              </el-col>
              <el-col :span="12">
                <dictCombox v-model="tableData.form.isIncludeStartDate"
                            dictType="include"
                            :style="{width: '100%'}"></dictCombox>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="观察结束日" class="dialog-form-item">
            <el-col :span="12">
              <el-date-picker value-format="YYYY-MM-DD" v-model="tableData.form.endDate"
                              type="date"
                              placeholder=""/>
            </el-col>
            <el-col :span="12">
              <dictCombox :span="12" v-model="tableData.form.isIncludeEndDate"
                          dictType="include"
                          :style="{width: '100%'}"></dictCombox>
            </el-col>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="观察频率" class="dialog-form-item">
            <dictCombox :span="12" v-model="tableData.form.frequency"
                        dictType="ObserFrequency"
                        :style="{width: '100%'}"></dictCombox>
          </el-form-item>
        </el-col>
      </el-row>
    </div>
    <vxe-toolbar ref="xToolbar" :loading="tableData.loading" width="50%">
      <template #buttons>
        <el-button type="primary" icon="plus" @click="insertEvent">新增</el-button>
        <el-button type="danger" icon="Delete" content="删除" @click="removeRowEvent">删除</el-button>
        <el-button type="reset" icon="Refresh" @click="reloadRowEvent">重置</el-button>
      </template>
    </vxe-toolbar>

    <vxe-table
        border
        align="center"
        show-overflow
        keep-source
        ref="xTable"
        width="70%"
        :column-config="{resizable: true}"
        class="myTable"
        :loading="tableData.loading"
        :data="tableData.data"
        :edit-rules="tableData.validRules"
        :edit-config="{trigger: 'click', mode: 'row', showUpdateStatus: true, showInsertStatus: true}">
      <vxe-column type="checkbox" width="30"></vxe-column>
      <vxe-column :edit-render="{}" field="endDate" title="敲出观察日">
        <template #default="{ row }">
          <span>{{ row.endDate }}</span>
        </template>
        <template #edit="{ row }">
          <el-date-picker value-format="YYYY-MM-DD" v-model="row.endDate"
                          type="date" style="text-align: center" :align='center'
                          placeholder=""/>
          <!--                <vxe-input v-model="row.floorPrice" type="text"></vxe-input>-->
        </template>
      </vxe-column>
      <vxe-column :edit-render="{}" field="levelPercentage" title="敲出障碍%">
        <template #default="{ row }">
          <span>{{ row.levelPercentage }}</span>
        </template>
        <template #edit="{ row }">
          <Numberinput :align='center' v-model="row.levelPercentage" precision="2" append="%"/>
        </template>
      </vxe-column>
      <vxe-column :edit-render="{}" field="paymentDate" title="敲出支付日">
        <template #default="{ row }">
          <span>{{ row.paymentDate }}</span>
        </template>
        <template #edit="{ row }">
          <el-date-picker value-format="YYYY-MM-DD" v-model="row.paymentDate"
                          type="date"
                          placeholder=""/>
        </template>
      </vxe-column>
      <!--      <vxe-column :edit-render="{}" field="floorPrice" title="计息天数">
              <template #default="{ row }">
                <span>{{ row.floorPrice }}</span>
              </template>
              <template #edit="{ row }">
                <InputAmount v-model:value="row.floorPrice" append="D" precision="4"></InputAmount>
                &lt;!&ndash;                <vxe-input v-model="row.floorPrice" type="text"></vxe-input>&ndash;&gt;
              </template>
            </vxe-column>-->
      <vxe-column :edit-render="{}" field="paymentAmountPecentage" title="敲出票息(%)">
        <template #default="{ row }">
          <span>{{ row.paymentAmountPecentage }}</span>
        </template>
        <template #edit="{ row }">
          <Numberinput v-model="row.paymentAmountPecentage" precision="2" append="%"/>
          <!--                <vxe-input v-model="row.floorPrice" type="text"></vxe-input>-->
        </template>
      </vxe-column>
      <!--      <vxe-column :edit-render="{}" field="floorPrice" title="现金收益">
              <template #default="{ row }">
                <span>{{ row.floorPrice }}</span>
              </template>
              <template #edit="{ row }">
                <InputAmount v-model:value="row.floorPrice" append="元" format="#,##0.####"></InputAmount>
                &lt;!&ndash;                <vxe-input v-model="row.floorPrice" type="text"></vxe-input>&ndash;&gt;
              </template>
            </vxe-column>-->
    </vxe-table>

  </div>

</template>

<script setup>
import {VXETable} from 'vxe-table'
import Numberinput from '@/xquant/base/number'
import InputAmount from '@/xquant/base/InputAmount'
import {generateOberserDates} from "../../common/common";
import {onMounted, reactive, getCurrentInstance, ref, watch} from 'vue'

const {proxy} = getCurrentInstance()
const xTable = ref({})
const labelWidth = ref('88px')
const tableData = reactive({
  loading: false,
  data: [],
  validRules: {},
  form: {
    startDate: '',
    endDate: '',
    isIncludeStartDate: '1',
    frequency: "",
    isIncludeEndDate: "1"
  },
  //父组件的form对象
  formData: {}
})
const props = defineProps({
  data: {
    type: Object,
    default: {}
  },
  setForm: {
    type: Function,
    default: {}
  },
  setDisable: {
    type: Function,
    default: {}
  }
})

onMounted(() => {
  tableData.formData = proxy.lsh.cloneDeep(props.data)
  tableData.form.startDate = tableData.formData.data.effectiveDate
  tableData.form.endDate = tableData.formData.data.terminationDate
  tableData.form.frequency = tableData.formData.data.ObserFrequency
  /*
  * tableData.formData.data.knockOutYieldYear 敲出年化 是否 0 1
  *
  * */
  tableData.data = tableData.formData.knocks.map(item => {
    return {
      endDate: item.observeDate.endDate,
      levelPercentage: Number(item.trigger.levelPercentage * 100).toFixed(2),
      paymentDate: item.paymentDate,
      paymentAmountPecentage: Number(item.basicYield.paymentAmountPecentage * 100).toFixed(2)
    }

  })

})


function saveEvent() {
  const $table = xTable.value
  const {insertRecords, removeRecords, updateRecords} = $table.getRecordset()
  if (insertRecords.length <= 0 && removeRecords.length <= 0 && updateRecords.length <= 0) {
    props.setDisable(true)
  }
  // $table.getTableData().tableData.some(element => {
  //   if (element.floorPrice > element.capPrice) {
  //     if (element.capPrice != '') {
  //       proxy.$modal.notify('行权下限必须小于上限')
  //       floorFlag = true
  //       return true
  //     }
  //   } else if (element.floorPrice == element.capPrice) {
  //     proxy.$modal.notify('行权下限必须小于上限')
  //     floorFlag = true
  //     return true
  //   }
  //   list.push({min: element.floorPrice, max: element.capPrice})
  // })
  proxy.$modal.notify('数据保存成功！')
  //将tableDate推给父组件的knocks
  tableData.formData.knocks = tableData.data.map(item => {
    return {
      'trigger': {
        'type': tableData.formData.data.knockType == '' ? 'EqualOrLess' : 'EqualOrGreater',
        // 'level': tableData.formData.data.strike,
        'levelPercentage': Number(item.levelPercentage / 100).toFixed(4)
      },
      'observeDate': {
        'endDate': item.endDate,
        'endDateConv': 'FOLLOWING',
        'calendar': 'CHINA_EX'
      },
      'calclationPeriod': {
        'startDate': tableData.formData.data.effectiveDate,
        'startDateConv': 'FOLLOWING',
        'isIncludeStartDate': tableData.form.isIncludeStartDate,
        'endDate': item.endDate,
        'endDateConv': 'FOLLOWING',
        'calendar': 'CHINA_EX',
        'isIncludeEndDate': tableData.form.isIncludeEndDate
      },
      'basicYield': {
        'paymentAmount': '',
        'paymentAmountPecentage': Number(item.paymentAmountPecentage / 100).toFixed(4),
        'daycounter': tableData.formData.data.knockOutYieldYear == '1' ? tableData.formData.data.daycounter : '',
        'participationRate': '1.0'
      },
      'minimumYields': [
        {
          'paymentAmount': '',
          'paymentAmountPecentage': Number(item.paymentAmountPecentage / 100).toFixed(4),
          'daycounter': tableData.formData.data.MarginYieldYear == '1' ? tableData.formData.data.daycounter : '',
          'participationRate': '1.0'
        }
      ],
      'paymentDate': item.paymentDate,
      'paymentDateOffset': '',
      'paymentDateConv': 'FOLLOWING',
      'paymentDateCalendar': 'CHINA_EX'
    }
  })

  props.setForm(tableData.formData)
}

const insertEvent = async () => {
  const $table = xTable.value
  const newRecord = {}
  const {row: newRow} = await $table.insert(newRecord)
  await $table.setActiveRow(newRow)
}

const removeSelectEvent = async () => {
  const $table = xTable.value
  await $table.removeCheckboxRow()
}

const reloadRowEvent = async () => {
  // props.setForm(tableData.formData)
  props.setDisable(false)
  generateOberserDates(tableData.formData).then((arr) => {
        tableData.data = arr.map(item => {
          return {
            endDate: item.observeDate.endDate,
            // knockType:item.observeDate.endDate,
            levelPercentage: Number(item.trigger.levelPercentage * 100).toFixed(2),
            paymentDate: item.paymentDate,
            paymentAmountPecentage: Number(item.basicYield.paymentAmountPecentage * 100).toFixed(2)
          }
        })
      }
  )
}


const removeRowEvent = async (row) => {
  const $table = xTable.value
  const checkboxRecords = $table.getCheckboxRecords()
  // let sectionsArr =  tableData.formData.data.sections.map(item=>item._X_ROW_KEY)
  checkboxRecords.forEach(item => {
    // let current = sectionsArr.indexOf(key)
    // tableData.formData.data.sections.splice(current, 1)
    // tableData.formData.data.sections.splice(current, 1)
    tableData.data = tableData.data.filter(a => {
      return a._X_ROW_KEY != item._X_ROW_KEY
    })
  })

}

defineExpose({saveEvent})


/*watch*/
watch(() => tableData.form.frequency, (nv,ov) => {
  if (nv==ov||ov=='') return
  tableData.formData.data.ObserFrequency = tableData.form.frequency
  // props.setForm(tableData.formData)
  reloadRowEvent()
},{immediate:false})

</script>

<style scoped>
.dialog-form-item {
  /*width: 1rem;*/
}

/deep/ .myTable .el-input--small .el-input__inner {
  text-align: center;
}
</style>
